package com.carkeeper.shop.controller;


import com.carkeeper.entity.PageResult;
import com.carkeeper.entity.Result;
import com.carkeeper.entity.StatusCode;
import com.carkeeper.shop.pojo.Store;
import com.carkeeper.shop.pojo.StoreDetail;
import com.carkeeper.shop.service.StoreDetailService;
import com.carkeeper.shop.service.StoreService;
import com.carkeeper.utile.QiniuUtils;
import com.github.pagehelper.Page;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/store")
public class StoreController {

    @Autowired
    private StoreService storeService;

    @Autowired
    private StoreDetailService storeDetailService;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String STORE_PIC_RESOURCES = "store_pic_resources";
    public static final String STORE_PIC_DB_RESOURCES = "store_pic_db_resources";


    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public PageResult findPage(@RequestParam Map searchMap, @PathVariable int page, @PathVariable  int size){
        Page<Store> pageList = storeService.findPage(searchMap, page, size);
        PageResult pageResult=new PageResult(pageList.getTotal(),pageList.getResult());
        return pageResult;
    }

    /**
     * 增加功能，添加store
     * @param store
     * @return
     */
    @PostMapping("/addStore")
    public Result addStore(@RequestBody Store store){
        try {
           /* String code = "";
            Random random = new Random();
            for (int i = 0; i < 6; i++) {
                code += random.nextInt(10);
            }
            store.setCode(code);*/

            String code = this.getIncre("code");
            store.setCode(code);
            //并且要判断商家全称不能一样
            String name = store.getName();
            Store store1 = new Store();
            store1.setName(name);
            Store store2 = storeService.findOne(store1);

            if (store2 == null){
                storeService.addStore(store);
            }else {
                return new Result(false,StatusCode.ERROR,"增加失败");
            }
            return new Result(true,StatusCode.OK,"增加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"增加失败");
        }
    }

    /**
     * 图片上传七牛云，链接返回前端
     * @param imgFile
     * @return
     */
    @GetMapping("/upload")
    public Result upload(MultipartFile imgFile){
        try {
            byte[] bytes = imgFile.getBytes();
            String originalFilename = imgFile.getOriginalFilename();
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf - 1);
            //使用UUID随机产生文件名称，防止同名文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            QiniuUtils.upload2Qiniu(bytes,fileName);
            // 图片存储到redis中
            redisTemplate.boundSetOps(STORE_PIC_RESOURCES).add(fileName);
            return new Result(true, StatusCode.OK,"上传成功",fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"上传失败");
        }
    }

    /**
     * 增加功能，添加storeDetail
     * @param storeDetail
     * @return
     */
    @PostMapping("/addStoreDetail")
    public Result addStoreDetail(@RequestBody StoreDetail storeDetail){
        try {
            storeDetailService.addStoreDetail(storeDetail);
            // 图片存储到redis中
            redisTemplate.boundSetOps(STORE_PIC_DB_RESOURCES).add(storeDetail.getBusinessLicenseUrl(),
                    storeDetail.getCorporationBackUrl(), storeDetail.getCorporationObverseUrl());
            return new Result(true,StatusCode.OK,"增加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"增加失败");
        }
    }

    /**
     * 编辑功能的数据回显
     * @param id
     * @return
     */
    @GetMapping("/findStoreById")
    public Result findStoreById(@RequestParam("id") String id){
        try {
            Store store = storeService.findStoreById(id);
            return new Result(true, StatusCode.OK, "查询成功", store);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "查询失败");
        }
    }

    /**
     * 编辑功能的数据回显
     * @param id
     * @return
     */
    @GetMapping("/findStoreDetailById")
    public Result findStoreDetailById(@RequestParam("id") String id){
        try {
            StoreDetail storeDetail = storeDetailService.findStoreDetailById(id);
            return new Result(true, StatusCode.OK, "查询成功", storeDetail);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "查询失败");
        }
    }

    /**
     * 编辑功能  (前端要把id存入到store中，要不没法判断)
    * @param store
     * @return
     */
    @PutMapping("/updateStore")
    public Result updateStore(@RequestBody Store store){
        try {
            storeService.updateStore(store);
            return new Result(true, StatusCode.OK, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "修改失败");
        }
    }


    /**
     * 编辑功能 (前端要把id存入到storeDetail中，要不没法判断)
     * @param storeDetail
     * @return
     */
    @PutMapping("/updateStoreDetail")
    public Result updateStoreDetail(@RequestBody StoreDetail storeDetail){
        try {
            storeDetailService.updateStoreDetail(storeDetail);
            // 图片存储到redis中，因为可能会被修改
            redisTemplate.boundSetOps(STORE_PIC_DB_RESOURCES).add(storeDetail.getBusinessLicenseUrl(),
                    storeDetail.getCorporationBackUrl(), storeDetail.getCorporationObverseUrl());
            return new Result(true, StatusCode.OK, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "修改失败");
        }
    }

    /**
     * 导出功能
     * @param response
     * @return
     * @throws IOException
     */

    @GetMapping("/report")
    public Result report(HttpServletResponse response) throws IOException {

        //在内存中创建一个Excel文件（工作簿）
        XSSFWorkbook excel = new XSSFWorkbook();
        //创建一个工作表对象
        XSSFSheet sheet = excel.createSheet("服务商");
        //在工作表中创建行对象
        XSSFRow title = sheet.createRow(0);
        //在行中创建单元格对象


        title.createCell(0).setCellValue("序号");
        title.createCell(1).setCellValue("汽修厂编码");
        title.createCell(2).setCellValue("汽修厂简称");
        title.createCell(3).setCellValue("联系人");
        title.createCell(4).setCellValue("联系电话");
        title.createCell(5).setCellValue("是否连锁");
        title.createCell(6).setCellValue("所在区域");
        title.createCell(7).setCellValue("状态");

        List<Store> storeList = storeService.findAll();
        for (int i = 0; i < storeList.size(); i++) {

            XSSFRow dataRow = sheet.createRow(i+1);
            Store store = storeList.get(i);
            dataRow.createCell(0).setCellValue(store.getId());
            dataRow.createCell(1).setCellValue(store.getCode());
            dataRow.createCell(2).setCellValue(store.getSimpleName());
            dataRow.createCell(3).setCellValue(store.getContactName());
            dataRow.createCell(4).setCellValue(store.getContactPhone());
            dataRow.createCell(5).setCellValue(store.getIsChain());
            dataRow.createCell(6).setCellValue(store.getAddress());
            dataRow.createCell(7).setCellValue(store.getStatus());

        }

        //创建一个输出流，通过输出流将内存中的Excel文件写到磁盘
       /* FileOutputStream out = new FileOutputStream(new File("e:\\bbb.xlsx"));
        excel.write(out);
        out.flush();
        excel.close();*/
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-Disposition","attachment;filename=report.xlsx");
        excel.write(out);
        out.flush();
        out.close();
        excel.close();

        return null;
    }

    //锁定状态的改变，0正常，1锁定
    @PutMapping("/updateStatus")
    public Result updateStatus(@RequestBody Store store){
        //每次点击都要将1切换成0或0切换成1，并且修改数据库
        try {
            Store store1 = storeService.findOne(store);
            if ("1".equals(store1.getStatus())){
                store1.setStatus("0");
                storeService.updateStore(store1);
            } else if ("0".equals(store1.getStatus())){
                store1.setStatus("1");
                storeService.updateStore(store1);
            }
            return new Result(true, StatusCode.OK, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "修改失败");
        }

    }


    /**
     * 获取递增的序列号
     *
     * @param prefix 生成序列号的前缀
     * @return
     */
    public String getIncre(String prefix) {
        //序列号前缀加特定标识，如系统模块名之类的 防止重复
        String key = "STORE_" + prefix;
        String increResult = null;
        try {
            //如果该key不存在 会自动创建，值为第二个参数delta
            //最终调用的还是jedis的incrBy(byte[] key, long value)方法
            Long increNum = redisTemplate.opsForValue().increment(key, 1);
            //不足补位
            increResult = String.format("%1$06d", increNum);
        } catch (Exception e) {
            //logger.infor("获取序列号失败");
            /*这里可以根据需求手动生成一个不重复的单号，
             * */
        }
        return increResult;
    }



}
